package robotter.bluecambot;

import robotter.bluecambot.game_element;
import robotter.bluecambot.configuration;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.util.Log;
import android.widget.TextView;

public class communication{
	private boolean isConnected=false;
	private WifiManager wifi_man=null;
	private boolean wifi_found=false;
	private int netid=-1;
	private bluecambot top_class=null;
	private TextView tv = null;
	
	public communication(bluecambot parent){
		Log.v("communication", "WiFi Connection");
		top_class=parent;
		
        wifi_man=(WifiManager)top_class.getSystemService(Context.WIFI_SERVICE);

		/* Initialisation and connection to WiFi */
		if (wifi_man.getWifiState()!=WifiManager.WIFI_STATE_ENABLED){
			Log.e("communication", "Error getting WiFi State, trying activation");
			wifi_man.setWifiEnabled(true);
		}

		IntentFilter intf= new IntentFilter();
		intf.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		top_class.registerReceiver(Wifi_list, intf);

       	tv = (TextView)top_class.findViewById(R.id.text);;
	    tv.setText("Can't find the network...");
		wifi_man.startScan();

		Log.v("communication", "List of Configured WiFi");
		for (WifiConfiguration config : wifi_man.getConfiguredNetworks()) {
		     	//if (config.BSSID==BSSID_ROBOT){
				if (config.SSID.equals("\""+configuration.comm_SSID_ROBOT+"\"")){
		     		Log.d("communication","***** NETWORK TO CONNECT TO *****");
		     		netid=config.networkId;
		     	}
		     	Log.d("communication","Wifi Configured:");
		     	Log.d("communication","  -> Net ID:"+config.networkId);
		     	Log.d("communication","  -> BSSID:"+config.BSSID);
		     	Log.d("communication","  -> Network name:"+config.SSID);
		     	Log.d("communication","  -> Network Auth. Algo.:"+config.priority);
		     	Log.d("communication","  -> Network status:"+config.status);
		     	Log.d("communication","-----------");
	    }
		
	}
	
	public int initConnection(){
		// Return -1 if the network is not configured
		// Return -2 waiting for the network
		// Return 0 if ok
		Log.v("communication", "Initialisation");
		
		if (netid==-1){
			Log.e("communication", "No configuration for robot network");
			tv.setText("Please configure the network...");
			isConnected=false;
			return -1;
		}
		if (!wifi_found){
			Log.e("communication", "Can't find the robot network");
			isConnected=false;
        	// Attente
        	SystemClock.sleep(5000);
			//return -2;
        	
        	// TODO
			isConnected=true;
			return 0;
		}else{
			top_class.unregisterReceiver(Wifi_list);
			wifi_man.enableNetwork(netid, true);
			isConnected=true;
			tv.setText("WiFi OK...");
			return 0;
		}

	}
	
	public boolean connected(){
		return isConnected;
	}
	
	public void send_data(List<game_element> detected_elem){
		Log.v("communication", "Sending data");
		if (!isConnected) {
			Log.e("communication", "No active connexion");
			return;
		}
		if (detected_elem==null){
			Log.e("communication", "Nothing to send");
			return;
		}
		
		// TODO
		
	}
	
	public void finalize(){
		Log.v("communication", "Closing communication");
		try{
			top_class.unregisterReceiver(Wifi_list);			
		}
		catch  (Throwable t) {
			Log.i("communication", "Can't unregister Wifi List");
		}

		if (!isConnected) {
			Log.e("communication", "No active connexion");
			return;
		}
		wifi_man.disconnect();

	}
	
	// Wifi discover and connect section
	BroadcastReceiver Wifi_list=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	Log.d("BroadcastReceiver","Reception of the scan results");
        	List<ScanResult> availableNetworks=wifi_man.getScanResults();

        	if(availableNetworks.isEmpty()){
        		Log.e("BroadcastReceiver","No Wifi Found");
        		return;
        	}

        	for (ScanResult result : availableNetworks) {
		     	//if (result.BSSID==comm_BSSID_ROBOT){
		     	if (result.SSID.equals(configuration.comm_SSID_ROBOT)){
		     		Log.d("BroadcastReceiver","***** NETWORK FOUND *****");
			     	wifi_found=true;
		     	}
		     	Log.d("BroadcastReceiver","Wifi Found:");
		     	Log.d("BroadcastReceiver","  -> BSSID:"+result.BSSID);
		     	Log.d("BroadcastReceiver","  -> Auth type:"+result.capabilities);
		     	Log.d("BroadcastReceiver","  -> Network name:"+result.SSID);
		     	Log.d("BroadcastReceiver","  -> Power Level:"+result.level+" dBm");
		     	Log.d("BroadcastReceiver","  -> Frequency:"+result.frequency+" Mhz");
		     	Log.d("BroadcastReceiver","-----------");
        	}
        }

      };

}
